import { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import './index.scss'
import { Ajax } from "../../utils/request";
import Nerv, { unmountComponentAtNode } from "nervjs";
import GPreviewer from '../../components/react-wx-images-viewer'

/**
 * 在新页面中全屏预览图片。预览的过程中用户可以进行保存图片、发送给朋友等操作。
 * @param {Object} object
 * @param {Array.<string>} object.urls 需要预览的图片链接列表。2.2.3 起支持云文件ID。
 * @param {string} [object.current=object.urls[0]]  urls的第一张 当前显示图片的链接
 * @param {function} [object.success] 接口调用成功的回调函数
 * @param {function} [object.fail] 接口调用失败的回调函数
 * @param {function} [object.complete] 接口调用结束的回调函数（调用成功、失败都会执行）
 */
const previewImage = ({ urls, current, success, fail, complete } = {}) => {
  const div = document.createElement('div')
  const currentIndex = urls.reduce((prev, curr, index) => curr.smallPhoto === current.smallPhoto ? index : prev, -1)
  const onSuccess = res => {
    success && success(res)
    complete && complete()
    return Promise.resolve(res)
  }
  const onError = res => {
    fail && fail(res)
    complete && complete()
    return Promise.reject(res)
  }
  const props = {
    urls,
    onClose () {
      unmountComponentAtNode(div)
    }
  }
  if (currentIndex > -1) {
    props.index = currentIndex
  }
  Nerv.render(<GPreviewer {...props} />, div)
  return onSuccess({ errMsg: 'previewImage:ok' })
}

/**
 * 首页
 * @author zeng
 * @date   2019/12/30 15:31
 */
class Index extends Component {

  state = {
    images: []
  }

  function

  /**
   * 获取浏览器参数
   * @author zeng
   * @date   2019/12/30 16:48
   */
  getUrlParam () {
    const args = {};
    const search = decodeURIComponent(location.search.substring(1));
    const arr = search.split('&');
    for (let i = 0, len = arr.length; i < len; i++) {
      const t = arr[i].split('=');
      args[t[0]] = t[1]
    }
    return args
  }

  componentWillMount () {
    const param = this.getUrlParam()
    const { urlPrefix, index } = param
    const data = { ...param }
    delete data.urlPrefix
    delete data.index
    Ajax.request({
      url: urlPrefix + '/product/findProductDetailById',
      data: Object.assign(data, {
        device: +data.device,
        actId: +data.actId,
        productId: +data.productId,
        productType: +data.productType,
        resType: +data.resType,
        scene: +data.scene,
        shareUser: +data.shareUser,
      }),
      success: ({ data }) => {
        const urls = data.pictureContentList
        previewImage({
          urls,
          current: urls[+index]
        })
      }
    })
  }

  render () {
    return (
      <View className='index' />
    )
  }
}

export default Index
